package com.example.jussi.servicedemo;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Intent intent;
    ServiceConnection connection;
    MyService.MyBind bind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(MainActivity.this, MyService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d(TAG, "onServiceConnected:");
                bind = (MyService.MyBind) iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d(TAG, "onServiceDisconnected: ");
            }
        };
    }

    public void bind(View hhView){
        Log.d(TAG, "bind: ");
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    public void unbind(View hhView){
        Log.d(TAG, "unbind: ");
        if(isServiceRunning()){
            unbindService(connection);
        }else{
            Toast.makeText(MainActivity.this,"It is not bind service", Toast.LENGTH_SHORT).show();
        }
    }

    public void getValue(View hhView){
        Toast.makeText(MainActivity.this, bind.getCount()+"", Toast.LENGTH_SHORT).show();
    }

    public void setValue(View hhView){
        bind.setCount(0);
    }

    private boolean isServiceRunning(){
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for(ActivityManager.RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)){
            if("com.example.jussi.servicedemo.MyService".equals(service.service.getClassName())){
                return true;
            }
        }
        return false;
    }
}
